package com.feiwo.nonego.rpc.common.scanner;

import com.feiwo.nonego.rpc.common.annotation.RpcReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;

import static java.lang.Class.forName;

/**
 * @author feiwo 2025-08-03
 */
public class RpcReferenceScanner extends ClassScanner {

    private static final Logger LOGGER = LoggerFactory.getLogger(RpcReferenceScanner.class);

    /**
     * 扫描指定包下带有@NonegoReference注解的字段，并记录相关信息
     *
     * @param scanPackage 需要扫描的包名
     * @return 包含处理结果的Map集合
     * @throws IOException 当扫描过程中发生IO异常时抛出
     */
    public static Map<String, Object> doScannerRpcReferenceAnnotation(String scanPackage) throws IOException {
        var handlerMap = new HashMap<String, Object>();
        // 获取指定包下的所有类名
        List<String> classNameList = getClassNameList(scanPackage);
        if (classNameList.isEmpty()) {
            return handlerMap;
        }

        // 遍历所有类，检查字段上的@NonegoReference注解
        classNameList.forEach(className -> {
            try {
                var clazz = Class.forName(className);
                var fields = clazz.getDeclaredFields();
                Stream.of(fields).forEach(field -> {
                    var rpcReference = field.getAnnotation(RpcReference.class);
                    if (Objects.nonNull(rpcReference)) {
                        // 设置字段可访问以防止 IllegalAccessException
                        field.setAccessible(true);

                        LOGGER.info("当前标注@RpcReference注解的字段名称 ---> {}", field.getName());
                        LOGGER.info("==========================================================");
                        LOGGER.info("服务类 ---> {}", rpcReference.registryType());
                        LOGGER.info("服务地址 ---> {}", rpcReference.registryAddress());
                        LOGGER.info("版本 ---> {}", rpcReference.version());
                        LOGGER.info("分组 ---> {}", rpcReference.group());
                    }
                });
            } catch (ClassNotFoundException e) {
                LOGGER.error("类未找到: {}", className, e);
            } catch (Exception e) {
                LOGGER.error("处理类 {} 时发生未知异常", className, e);
            }
        });

        return handlerMap;
    }


}
